package co.za.itweb.brainstormlite;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.util.ByteArrayBuffer;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class BrainActivity extends Activity {
	RefreshTask rt;
	TextView txt;
	TextView txtloaded;
	AnimationSet animation;
	Animation fadeOut;
	Animation fadeIn; 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_brain);
		int colors[] = { Color.parseColor("#FF0c0d0f"),
				Color.parseColor("#FF0c0d0f") };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		this.getWindow().setBackgroundDrawable(grad);
		
		//blink();
		

		
		if (internetConnection()) {

			rt = new RefreshTask(this);
			if (rt.getStatus() == AsyncTask.Status.PENDING) {
				// My AsyncTask has not started yet
				rt.execute();
			}

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				// My AsyncTask is currently doing work in doInBackground()
			}

			if (rt.getStatus() == AsyncTask.Status.FINISHED) {
				// My AsyncTask is done and onPostExecute was called

			}

		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"There is no internet connection.Please connect to the internet and try again.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
									finish();
								}

							});
			AlertDialog alert = builder.create();
			alert.show();

		}
		
		txt = (TextView) findViewById(R.id.txt);
		txtloaded = (TextView) findViewById(R.id.txtloaded);
		
		 fadeIn = new AlphaAnimation(0, 1);
		fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
		fadeIn.setDuration(600);

		 fadeOut = new AlphaAnimation(1, 0);
		fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
		fadeOut.setStartOffset(600);
		fadeOut.setDuration(600);

		animation = new AnimationSet(false); //change to false
		animation.addAnimation(fadeIn);
		animation.addAnimation(fadeOut);
		txt.setText("Loading");
		
		//txt.startAnimation(AnimationUtils.loadAnimation(BrainActivity.this, R.anim.fadein));
		
        blink();
	}
	
	 private void blink(){
		    final Handler handler = new Handler();
		    new Thread(new Runnable() {
		        @Override
		        public void run() {
		        int timeToBlink = 1200;    //in milissegunds
		        try{Thread.sleep(timeToBlink);}catch (Exception e) {}
		            handler.post(new Runnable() {
		                @Override
		                    public void run() {
		                	 
		                    if(txt.isShown()){
		                    	//txt.setAnimation(animation);
		                    	txt.startAnimation(AnimationUtils.loadAnimation(BrainActivity.this, R.anim.fadein));
		                    	txt.startAnimation(AnimationUtils.loadAnimation(BrainActivity.this, R.anim.fadeout));
		                        //txt.setVisibility(View.GONE);
		                    }else{
		                    	
		                       // txt.setVisibility(View.VISIBLE);
		                    }
		                    blink();
		                }
		                });
		            }
		        }).start();
		    }

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	@SuppressLint("ParserError")
	private class RefreshTask extends AsyncTask<Void, Integer, Void> {

		RSSFeed feed;

		public RefreshTask(BrainActivity activity) {

		}

		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... params) {
			for (int o = 0; o < MenuActivity.feeds.length; o++) {
				if(o!=7){
				if(DownloadFromUrl(MenuActivity.feeds[o],MenuActivity.feedslocal[o])){
				
				feed = parseLocalXml(Environment.getExternalStorageDirectory() + "/co.za.itweb.brainstormlite/"+MenuActivity.feedslocal[o]);
				
				
				}
				if (feed != null) {
					MenuActivity.fList.add(o,feed);
					publishProgress(o);
					if (isCancelled()) {

						MenuActivity.fList.clear();

						Intent returnIntent = new Intent();
						returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						setResult(RESULT_CANCELED, returnIntent);
						finish();

						return null;
					}

				}else{
					MenuActivity.fList.add(o,null);
				}
				}

			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			publishProg(values[0]);
		
			
		}

		@Override
		protected void onPostExecute(Void result) {

			if (MenuActivity.fList.size() > 1) {

				Intent returnIntent = new Intent();

				setResult(RESULT_OK, returnIntent);
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				finish();
			} else {
				Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(RESULT_CANCELED, returnIntent);
				finish();
			}

		}
	}
	
	public void publishProg(Integer x){
		
		txtloaded.setText( MenuActivity.feedslocal[x]);
		
	}

	public  RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println(ee.toString()
					+ "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			return null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_HOME)) {

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {

				rt.cancel(true);
			}
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_CANCELED, returnIntent);

			finish();

		}
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {

				rt.cancel(true);
			}
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_CANCELED, returnIntent);
			finish();

		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		if (rt.getStatus() == AsyncTask.Status.RUNNING) {

			rt.cancel(true);
		}

		Intent returnIntent = new Intent();
		returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		setResult(RESULT_CANCELED, returnIntent);

		finish();
		return;
	}
	
	
	
	public static RSSFeed parseLocalXml(String filename){
		try {

			//URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(new FileInputStream(filename));
			
			xmlreader.parse(is);

			System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
					+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
					+ ee.toString());
			return null;
		}
	}
	
	
	
	public static  boolean DownloadFromUrl(String DownloadUrl, String fileName) {

		   try {
		           File root = android.os.Environment.getExternalStorageDirectory();               

		           File dir = new File (Environment.getExternalStorageDirectory() + "/co.za.itweb.brainstormlite/");
		           if(dir.exists()==false) {
		                dir.mkdirs();
		           }

		           URL url = new URL(DownloadUrl); //you can write here any link
		           File file = new File(dir, fileName);

		           long startTime = System.currentTimeMillis();
		           Log.d("DownloadManager", "download begining");
		           Log.d("DownloadManager", "download url:" + url);
		           Log.d("DownloadManager", "downloaded file name:" + fileName);

		         
		           URLConnection ucon = url.openConnection();

		           InputStream is = ucon.getInputStream();
		           BufferedInputStream bis = new BufferedInputStream(is);

		          
		           ByteArrayBuffer baf = new ByteArrayBuffer(100*1024);
		           int current = 0;
		           while ((current = bis.read()) != -1) {
		              baf.append((byte) current);
		           }


		       
		           FileOutputStream fos = new FileOutputStream(file);
		           fos.write(baf.toByteArray());
		           fos.flush();
		           fos.close();
		           
		           Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
                   return true;
		   } catch (IOException e) {
		       Log.d("DownloadManager", "Error: " + e);
		       return false;
		   }

		}
	
	

}